<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\coupon\Coupon as CouponCoupon;
use app\common\model\coupon\Log;
use app\common\model\User;
use Exception;

/**
 * 优惠券接口
 */
class Coupon extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];
    /**
     * 优惠券列表
     *
     */
    public function list()
    {

        $ids =  Log::where('user_id', $this->auth->id)->column('coupon_id');
        $coupon = CouponCoupon::whereNotIn('id', $ids)->paginate(10);
        $this->success('请求成功', $coupon);
    }
    /**
     * 优惠券领取
     *
     */
    public function receive()
    {
        $post = request()->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        try {
            Log::getCoupon($id, $this->auth->id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取成功');

        // $coupon = CouponCoupon::get($id)->toArray();
        // $coupon['user_id'] = $this->auth->id;
        // $coupon['coupon_id'] = $coupon['id'];
        // if ($coupon['workrange']) {
        //     $workrange = explode(' - ', $coupon['workrange']);
        //     $coupon['startdate'] = $workrange[0];
        //     $coupon['enddate'] = $workrange[1];
        // }
        // $check = Log::where('user_id', $this->auth->id)->where('coupon_id', $id)->count();
        // if ($check) {
        //     $this->error('【' . $coupon['name'] . '】优惠券已领取');
        // }

        // unset($coupon['id']);
        // unset($coupon['workrange']);
        // $couponLog = new Log();

        // $res = $couponLog->allowField(true)->save($coupon);
        // if ($res) {
        //     $this->success('领取成功');
        // }
        // $this->error('领取失败');
    }
    /**
     * 我的优惠券
     *
     */
    public function myCoupon()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        try {
            $user_id =  $this->auth->id;
            $couponLog = new Log();
            $list = $couponLog->getUseCoupon($type, $pay_type, $user_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('请求成功', $list);
    }
}
